package fi.hell.lunchit
import java.math.RoundingMode

class RoundController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [roundInstanceList: Round.list(params), roundInstanceTotal: Round.count()]
    }

    def create = {
        def roundInstance = new Round()
        roundInstance.properties = params
        return [roundInstance: roundInstance]
    }

    def save = {
        def roundInstance = new Round(params)
        if (roundInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'round.label', default: 'Round'), roundInstance.id])}"
            redirect(action: "show", id: roundInstance.id)
        }
        else {
            render(view: "create", model: [roundInstance: roundInstance])
        }
    }

    def show = {
        def roundInstance = Round.get(params.id)
        if (!roundInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'round.label', default: 'Round'), params.id])}"
            redirect(action: "list")
        }
        else {
            [roundInstance: roundInstance]
        }
    }

    def edit = {
        def roundInstance = Round.get(params.id)
        if (!roundInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'round.label', default: 'Round'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [roundInstance: roundInstance]
        }
    }

    def update = {
        def roundInstance = Round.get(params.id)
        String referer = request.getHeader("Referer")

        if (roundInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (roundInstance.version > version) {
                    
                    roundInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'round.label', default: 'Round')] as Object[], "Another user has updated this Round while you were editing")
                    render(view: "edit", model: [roundInstance: roundInstance])
                    return
                }
            }

            try {
                params.price = params.price.replaceAll(',','\\.')
                BigDecimal price = (params.double('price'))
                params.originalPrice = price.setScale(2, RoundingMode.HALF_UP).unscaledValue()
            } catch (Exception e) {
                params.price = 0
                flash.message = "${message(code: 'round.price.invalid', args: [params.price], default:"Invalid price: {0}")}"
            }

            params.luncheonVoucherUsed = (params.luncheonVoucherUsed) ? true : false
            if (params.luncheonVoucherUsed) {
                Company c = User.getLoggedInUser()?.company
                params.price = Math.max(params.originalPrice - c?.luncheonVoucherProfitValue, c?.luncheonVoucherTotalValue - c?.luncheonVoucherProfitValue)
            } else {
                params.price = params.originalPrice
            }

            roundInstance.properties = params
            if (!roundInstance.hasErrors() && roundInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'round.label', default: 'Round'), roundInstance.id])}"

                if (referer && params.userUpdate) {
                    redirect(url:referer)
                } else {
                    redirect(action: "show", id: roundInstance.id)
                }
            }
            else {
                if (referer && params.userUpdate) {
                    flash.message = "${message(code:'round.couldNotSaveSelection', default:'Could not save your selection. Plase make sure you selected a restaurant.')}"
                    redirect(url:referer)
                } else {
                    render(view: "edit", model: [roundInstance: roundInstance])
                }
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'round.label', default: 'Round'), params.id])}"
            if (referer && params.userUpdate) {
                redirect(url:referer)
            } else {
                redirect(action: "list")
            }
        }
    }

    def delete = {
        def roundInstance = Round.get(params.id)
        if (roundInstance) {
            try {
                roundInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'round.label', default: 'Round'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'round.label', default: 'Round'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'round.label', default: 'Round'), params.id])}"
            redirect(action: "list")
        }
    }
    
    def confirm = {
    	Round currentRound = Round.currentRound()
    	currentRound.confirmed = true
    	currentRound.save(flush:true)
    	redirect(url:grailsApplication.config.grails.serverURL)
    }

    def setPrice = {
        Round currentRound = Round.currentRound()

        try {
            params.price = params.price.replaceAll(',','\\.')
            BigDecimal price = (params.double('price'))
            currentRound.originalPrice = price.setScale(2, RoundingMode.HALF_UP).unscaledValue()
        } catch (Exception e) {
            params.price = 0
            flash.message = "${message(code: 'round.price.invalid', args: [params.price], default:"Invalid price: {0}")}"
        }

        currentRound.luncheonVoucherUsed = (params.luncheonVoucherUsed) ? true : false
        if (params.luncheonVoucherUsed) {
            Company c = User.getLoggedInUser()?.company
            currentRound.price = Math.max(currentRound.originalPrice - c?.luncheonVoucherProfitValue, c?.luncheonVoucherTotalValue - c?.luncheonVoucherProfitValue)
        } else {
            currentRound.price = currentRound.originalPrice
        }

    	currentRound.save(flush:true)
    	redirect(url:grailsApplication.config.grails.serverURL)
    }
}
